package com.linkallcloud.core.query.rule;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.TypeReference;
import com.alibaba.fastjson2.reader.ObjectReader;
import com.linkallcloud.core.query.rule.desc.ObjectRuleDescriptor;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author qbk
 * @date 2022/11/7
 */
@Slf4j
public class QueryRuleDeserializer implements ObjectReader<List<QueryRule>> {

    @Override
    public List<QueryRule> readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {
        if (jsonReader.readIfNull()) {
            return null;
        }
        try {
            String s = jsonReader.readString();
            if (StrUtil.isNotBlank(s)) {
                JSONArray rs = JSONArray.parseArray(s);
                if (rs != null && rs.size() > 0) {
                    List<QueryRule> res = new ArrayList<>();
                    for (int i = 0; i < rs.size(); i++) {
                        JSONObject jsonObject = rs.getJSONObject(i);
                        String field = jsonObject.getString("field");
                        Object data = jsonObject.getObject("value", new TypeReference<Object>() {
                        });
                        Object op = jsonObject.getObject("op", new TypeReference<Object>() {
                        });
                        ObjectRuleDescriptor rd = new ObjectRuleDescriptor(field, op, data);
                        QueryRule[] queryRules = QueryRuleFactory.create(rd);
                        if (queryRules != null && queryRules.length > 0) {
                            res.addAll(List.of(queryRules));
                        }
                    }
                    if (res.size() > 0) {
                        return res;
                    }
                }
            }
        } catch (Exception e) {
            log.error("QueryRuleDeserializer error:", e);
        }
        return null;
    }
}
